package com.csweimei.rentmanagementtreasure.tenant.viewModel;

import android.app.Application;
import android.content.Intent;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.csweimei.rentmanagementtreasure.http.entity.BaseResult;
import com.csweimei.rentmanagementtreasure.http.entity.HouseInfoDetailBean;
import com.csweimei.rentmanagementtreasure.tenant.ui.act.customer.ChooseCustomerActivity;
import com.csweimei.rentmanagementtreasure.utils.GlideEngine;
import com.csweimei.rentmanagementtreasure.utils.GlideHandler;
import com.csweimei.rentmanagementtreasure.utils.ValidateUtils;
import com.csweimei.rentmanagementtreasure.utils.permission.RxPermissionsUtils;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunBean;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUpload;
import com.csweimei.rentmanagementtreasure.utils.uploadUtils.QiNiuYunUploadCallBack;
import com.csweimei.rentmanagementtreasure.viewModel.TitleVM;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AddHouseFVM extends TitleVM {
    public ObservableField<HouseInfoDetailBean> houseInfo = new ObservableField<>();
    public ObservableField<String> imgs = new ObservableField<>("");

    public ObservableField<String> customid = new ObservableField<>();
    public ObservableField<String> customer = new ObservableField<>();
    public ObservableField<String> FollowTime = new ObservableField<>();
    public ObservableField<String> FollowType = new ObservableField<>();
    public ObservableField<String> FollowInfo = new ObservableField<>();
    public ObservableField<String> FollowImg = new ObservableField<>();

    public AddHouseFVM(@NonNull Application application, BaseModel model) {
        super(application, model);
        setTitleText("添加记录");
    }

    public BindingCommand selTime = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            TimePickerView pvTime = new TimePickerBuilder(mActivity, (date, v) -> {
                FollowTime.set(new SimpleDateFormat("yyyy-MM-dd").format(date));
            })
                    .setType(new boolean[]{true, true, true, false, false, false})
                    .setLabel("年", "月", "日", "", "", null)
                    .build();
            pvTime.show();
        }
    });

    public BindingCommand selCustomer = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Intent intent = new Intent(mActivity, ChooseCustomerActivity.class);
            mActivity.startActivityForResult(intent,10086);
        }
    });

    public BindingCommand selImg = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            RxPermissionsUtils.file(mActivity, (RxPermissionsUtils.Accept) () -> {
                PictureSelector.create(mActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .isDisplayCamera(false)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setMaxSelectNum(1)
                        .setMinSelectNum(1)
                        .setImageSpanCount(4)
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                imgs.set(result.get(0).getRealPath());
                                GlideHandler.loadLifeWm(mActivity,imgs.get(),imageView,10);
                                getQNYToken();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        }
    });

    ImageView imageView;
    public void setImg(ImageView img) {
        imageView = img;
    }

    /**
     * 获取七牛云token
     */
    private void getQNYToken() {
        model.getToken()
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<QiNiuYunBean>() {
                    @Override
                    public void onNext(QiNiuYunBean qiniuYunBean) {
                        if (ValidateUtils.isNotEmptyObjectOrString(qiniuYunBean) &&
                                ValidateUtils.isNotEmptyString(qiniuYunBean.getToken())) {
                            uploadQNY(qiniuYunBean.getToken());
                        } else {
                            ToastUtils.showShort( "请求失败，请联系管理员");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void uploadQNY(String token) {
        String suffix = imgs.get().substring( imgs.get().lastIndexOf("."));
        String key = "works/zgb/" + System.currentTimeMillis() + suffix;
        QiNiuYunUpload.uploadFileToQny(mActivity, imgs.get(), token, key, new QiNiuYunUploadCallBack() {
            @Override
            public void onSuccess(String url) {
                FollowImg.set(url);
            }

            @Override
            public void onFail() {

            }

            @Override
            public void onProgress(String key, double progress) {

            }
        });

    }


    public BindingCommand saveRecord = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            postData();
        }
    });

    private void postData() {
        if (ValidateUtils.isEmptyString(FollowTime.get())){
            ToastUtils.showShort("请选择跟进时间");
            return;
        }
        if (ValidateUtils.isEmptyString(FollowInfo.get())){
            ToastUtils.showShort("请输入跟进内容");
            return;
        }
        if (ValidateUtils.isEmptyString(FollowImg.get())){
            ToastUtils.showShort("请选择跟进图片");
            return;
        }

        Map<String,String> map = new HashMap<>();
        map.put("userid",model.getLoginInfo().getData().getUser_id());
        map.put("customid",customid.get());
        map.put("FollowTime",FollowTime.get());
        map.put("FollowType",FollowType.get());
        map.put("housingID",houseInfo.get().getData().getId()+"");
        map.put("FollowInfo",FollowInfo.get());
        map.put("FollowImg",FollowImg.get());

        model.addfollow(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<BaseResult>() {
                    @Override
                    public void onNext(BaseResult bean) {
                        if (bean.issucc){
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }
}
